<template>
  <div class="question-container">
    <el-card class="box-card">
      <div slot="header">{{ $route.query.id ? '试题修改' : '试题录入' }}</div>
      <div>
        <el-form :model="subjectForm" :rules="rules" ref="subjectForm" label-width="120px" class="question-form">
          <!-- 学科 -->
          <el-form-item label="学科:" prop="subjectID">
            <el-select v-model="subjectForm.subjectID" placeholder="请选择" @change="handelCatalog">
              <el-option v-for="item in subjectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录:" prop="catalogID">
            <el-select v-model="subjectForm.catalogID" placeholder="请选择">
              <el-option v-for="item in catalogList" :key="item.id" :label="item.directoryName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select v-model="subjectForm.enterpriseID" placeholder="请选择">
              <el-option v-for="item in companysList" :key="item.id" :label="item.company" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <!-- 下一级的city 得先有province才能去继续选中city-->
          <el-form-item label="城市:" prop="city">
            <el-select style="width: 198px" v-model="subjectForm.province" placeholder="请选择" @change="changeProvince">
              <el-option v-for="item in citySelect.province" :key="item" :label="item" :value="item"></el-option>
            </el-select>

            <el-select style="width: 198px; margin-left: 4px" v-model="subjectForm.city" placeholder="请选择">
              <el-option v-for="item in citySelect.cities" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向:" prop="direction">
            <el-select v-model="subjectForm.direction" placeholder="请选择">
              <el-option v-for="item in directionList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型:" prop="questionType">
            <el-radio-group v-model="subjectForm.questionType" @change="changeRadio({})">
              <el-radio v-for="item in questionTypeList" :key="item.value" :label="item.value + ''">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度:" prop="difficulty">
            <el-radio-group v-model="subjectForm.difficulty">
              <el-radio v-for="item in difficulty" :key="item.value" :label="item.value + ''">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干:" prop="question">
            <quill-editor v-model="subjectForm.question" :options="editorOptions"></quill-editor>
          </el-form-item>

          <!-- 选项 分情况-->
          <el-form-item label="选项：" v-if="subjectForm.questionType !== '3'">
            <div class="option_item" v-for="(item, index) in subjectForm.options" :key="item.code">
              <!-- 事件函数 单选效果 -->
              <el-radio v-if="subjectForm.questionType === '1'" @change="changeRadio(item)" v-model="item.isRight" style="margin-right: 0" :label="true">{{ item.code }}：</el-radio>
              <el-checkbox v-if="subjectForm.questionType === '2'" v-model="item.isRight" style="margin-right: 0" :label="true">{{ item.code }}：</el-checkbox>
              <el-input v-model="item.title" style="width: 356px"></el-input>
              <UploadImage @changeImg="imgURL(index, $event)" :img="item.img" v-if="$route.query.id"></UploadImage>
              <UploadImage @changeImg="imgURL(index, $event)" v-else></UploadImage>
            </div>
            <!-- 添加按钮 -->
            <el-button type="danger" :disabled="subjectForm.questionType !== '2'" size="small" @click="addClick">+增加选项与答案</el-button>
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频:">
            <el-input v-model="subjectForm.videoURL"></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item label="答案解析:" prop="answer">
            <quill-editor v-model="subjectForm.answer" :options="editorOptions"></quill-editor>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注:">
            <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="subjectForm.remarks" style="width: 400px"> </el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item label="试题标签:">
            <el-select multiple v-model="subjectForm.tags" placeholder="请选择试题标签">
              <el-option v-for="item in tagList" :key="item.value" :label="item.label" :value="item.label"> </el-option>
            </el-select>
          </el-form-item>
          <!-- 确认提交/修改 -->
          <!--  添加还是修改做判断 根据路由 -->
          <el-form-item v-if="true">
            <el-button v-if="!this.$route.query.id" type="primary" @click="submit()">确认提交</el-button>
            <el-button v-else type="success" @click="modify()">确认修改</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
//获取图片
import UploadImage from '@/module-hmmm/components/upload-img'
// 学科
import { simple } from '@/api/hmmm/subjects.js'
//目录
import { list as getCataloglist } from '@/api/hmmm/directorys.js'
//标签
import { simple as getTagList } from '../../api/hmmm/tags.js'
// 方向 题型 难度
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
// 企业
import { list } from '@/api/hmmm/companys.js'
// 城市
import { provinces, citys } from '@/api/hmmm/citys.js'
//题目信息
import { add, update, detail } from '@/api/hmmm/questions.js'
//高亮
import hljs from 'highlight.js'
export default {
  name: 'QuestionsNew',
  components: {
    UploadImage
  },
  data() {
    return {
      //富文本编辑器
      editorOptions: {
        placeholder: '请输入内容....',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote'], // 引用，
            ['code-block', 'image', 'link'] // 代码块 、上传图片、链接
          ],
          // 语法高亮
          syntax: {
            highlight: (text) => hljs.highlightAuto(text).value
          }
        }
      },
      subjectForm: {
        subjectID: '', // 学科名称id
        catalogID: '', // 目录id
        enterpriseID: '', // 企业id
        province: '', // 省
        city: '', // 城市
        direction: '', // 方向
        tags: '', // 标签
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        // 点击选中变成true,表示是正确答案
        options: [
          { code: 'A', title: '', img: '', isRight: false },
          { code: 'B', title: '', img: '', isRight: false },
          { code: 'C', title: '', img: '', isRight: false },
          { code: 'D', title: '', img: '', isRight: false }
        ],
        answer: '', // 答案解析
        remarks: '', // 题目备注
        videoURL: '' // 解析视频
      },
      subjectList: [], // 学科列表
      directionList: direction, // 方向列表
      companysList: [], // 企业列表
      catalogList: [], // 目录列表
      tagList: [], // 标签列表
      questionTypeList: questionType, // 题型
      difficulty, // 难度
      citySelect: {
        // 城市
        province: [],
        cities: []
      },

      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'change' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        province: [{ required: true, message: '请选择城市', trigger: 'change' }],
        city: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'change' }],
        question: [{ required: true, message: '请输入题干', trigger: 'change' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getSubjectList()
    this.getCompanysList()
    this.getCityData()
    if (this.$route.query.id) {
      this.getQuestionsDetail()
    }
  },

  methods: {
    // 获取学科
    async getSubjectList() {
      const { data } = await simple()
      this.subjectList = data
    },
    // 获取目录列表
    async getList(id) {
      // 获取目录列表
      const { data: data1 } = await getCataloglist({ subjectID: id })
      this.catalogList = data1.items
      // 获取标签列表
      const { data: data2 } = await getTagList({ subjectID: id })
      this.tagList = data2
    },
    // 学科改变后
    handelCatalog(id) {
      this.getList(id)
    },
    // 获取企业
    async getCompanysList() {
      const { data } = await list()
      this.companysList = data.items
    },
    // 获取省份
    getCityData() {
      this.citySelect.province = provinces()
    },
    //获取城市 根据省份
    changeProvince(e) {
      this.citySelect.cities = citys(e)
    },
    // 获取图片地址
    imgURL(index, url) {
      this.subjectForm.options[index].img = url
    },
    //添加选项
    addClick() {
      this.subjectForm.options.push({
        isRight: false,
        // String.fromCharCode(65) 65表示A
        code: String.fromCharCode(65 + this.subjectForm.options.length),
        title: '',
        img: ''
      })
    },
    //改成单选效果
    changeRadio(item) {
      //先清空多选时的内容
      this.subjectForm.options.forEach((item) => {
        item.isRight = false
      })
      item.isRight = true
    },
    //修改题目时 回显信息
    async getQuestionsDetail() {
      const { data } = await detail({ id: this.$route.query.id })
      // console.log(data.tags)
      data.tags = data.tags.split(',')
      data.options = data.options.map((item) => {
        item.isRight = item.isRight === 1
        return item
      })
      this.subjectForm = data
      this.getList(this.subjectForm.subjectID)
      // 滚动顶部
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },

    //提交
    submit() {
      this.$refs.subjectForm.validate(async (valid) => {
        if (!valid) {
          //添加
          this.$message.error('请完整填写')
        } else {
          // const data = this.subjectForm
          //需要string 本身是数组 用join转换
          // data.tags = data.tags.join(',')
          // console.log(data.tags)
          const res = await add({ ...this.subjectForm, tags: this.subjectForm.tags.join(',') })
          this.$message.success('添加成功')
          //成功后跳转
          this.$router.push('/questions/list')
        }
      })
    },
    //修改
    modify() {
      this.$refs.subjectForm.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await update({ ...this.subjectForm, tags: this.subjectForm.tags.join(',') })
        this.$message.success('修改成功')
        this.$router.push('/questions/list')
      })
    }
  }
}
</script>

<style scoped lang='scss'>
.question-container {
  padding: 20px;
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: '';
  }
  .clearfix:after {
    clear: both;
  }

  .box-card {
    width: 100%;
  }

  ::v-deep {
    .el-select {
      height: 36px;
      width: 400px;
    }
    .el-textarea__inner {
      min-height: 100px;
    }
    .option_item {
      padding-bottom: 20px;
    }
    .ql-editor {
      height: 200px;
    }
  }
}
</style>